<?php
require_once("inc.admin.php");

$this_title="$vars[admin_title] &raquo; ".__("Member Sales");
$page_title=__("Member Sales");

if(!$pv["task"]["Sales"]){
	$errmsg="<h2>$page_title</h2>".format_err(__("You do not have the privilege to manage Member Sales."));

	print format_admin_page($errmsg, $this_title);
	exit();
}

$add_edit_file=$vars["file"]["admin"]["add_edit_sales"];

$item_per_page=$vars["admin_item_per_page"];

$r_sale_point = $vars['dbv']['sale_point'];

$search_options["member_sale"]["option"] = $r_member_sale=$vars['dbv']['member_sale'];
$search_options["member_sale"]["option_display"] = $r_member_sale_d=$vars['dbv']['member_sale_d'];
$search_options["member_sale"]["display"] = __("Member Sale");
$search_options["status"]["option"] = $r_status=array("confirmed","cancelled");
$search_options["status"]["option_display"] = $r_status_d=array("confirmed"=>__("Confirmed"),"cancelled"=>__("Cancelled"));
$search_options["status"]["display"] = __("Status");
$search_options["first_sale"]["option"] = $r_first_sale=array("y","n");
$search_options["first_sale"]["option_display"] = $r_first_sale_d=array("y"=>__("Yes"),"n"=>__("No"));
$search_options["first_sale"]["display"] = __("Plan A");
$search_options["stockist_sale"]["option"] = $r_stockist_sale=array("y","n");
$search_options["stockist_sale"]["option_display"] = $r_stockist_sale_d=array("y"=>__("Yes"),"n"=>__("No"));
$search_options["stockist_sale"]["display"] = __("Stockist Sales");
$search_options["payment_type"]["option"] = $r_payment_channel=$vars['dbv']['sale_payment'];
$search_options["payment_type"]["option_display"] = $r_payment_channel_d=$vars['dbv']['sale_payment_d'];
$search_options["payment_type"]["display"] = __("Payment Channel");
$search_options["collected"]["option"] = $r_collected_type = array("y","n");
$search_options["collected"]["option_display"] = $r_collected_type_d = array("y"=>__("Collected"),"n"=>__("Uncollected"));
$search_options["collected"]["display"] = __("Products Collected");

//#####SEARCH#####
if($_GET["s"]){
 $searching=1;
 $search_query=msales_search($_GET);
}

//textbox search, prefix "_sp_"
$r_textsearch=array("id"=>__("Sales ID"),"prefno"=>__("Product Ref #"),"uid"=>__("User ID"),"sid"=>__("Stockist ID"),"nm_name"=>__("Non-member Name"),"nm_contact"=>__("Non-member Contact"));

//custom search fields
$fromdate_search=generate_dmy_input("_sdf", $get_s["_sdf_day"], $get_s["_sdf_month"], $get_s["_sdf_year"], "class='inputbox'", 2009);
$todate_search=generate_dmy_input("_sdt", $get_s["_sdt_day"], $get_s["_sdt_month"], $get_s["_sdt_year"], "class='inputbox'", 2009);
$custom_date['title']=__("Date");
$custom_date['value']=__("From")." ".$fromdate_search."<br />".__("To")." ".$todate_search;

$searchfields_ordering=array("id","prefno","uid","member_sale","nm_name","nm_contact","stockist_sale","sid","first_sale","payment_type","collected","status",$custom_date);
$search_ui=build_admin_search_ui($searching, $this_file, $search_options, $r_textsearch, $searchfields_ordering, $inputbox_style);
//#####END SEARCH#####

//#####LIST MEMBER SALES#####
if($searching){
	$count_sql=$search_query["count_sql"];
	$record_sql=$search_query["record_sql"];
	foreach($r_sale_point as $point_type){
		$point_sql[$point_type] = $search_query[$point_type."_sql"];
	}
}else{
	$count_sql="select count(*) from $db->purchase";
	foreach($r_sale_point as $point_type){
		$point_sql[$point_type] = "select sum(total_$point_type) from $db->purchase";
	}
	$record_sql="select * from $db->purchase order by id limit <%limit_start%>, <%limit%>";
}

$cur_page=$_GET["nav"];
$total_record=@mysql_result(mysql_query($count_sql), 0);
$total_page=ceil($total_record/$item_per_page);
$page=($cur_page? ($cur_page>$total_page? $total_page : ($cur_page<1? 1 : $cur_page)) : 1);
$limit_start=($page-1)*$item_per_page;
$nav_link=format_page_admin($page, $total_page, $this_file);
$this_page_total=@mysql_num_rows($r=mysql_query(str_replace("<%limit_start%>", $limit_start, str_replace("<%limit%>", $item_per_page, $record_sql))));
$k=0;
foreach($r_sale_point as $point_type){
	$total_point[$point_type]=@mysql_result(mysql_query($point_sql[$point_type]), 0) or 0;
	$point_list.=" ".replace_tag(__("Total <%title%>: <%x%>."), array("<%title%>"=>__(strtoupper($point_type)), "<%x%>"=>number_format($total_point[$point_type], 2)));
}
for($i=0;$i<$this_page_total;$i++){
	$sale=mysql_fetch_assoc($r);
	$edit_link="<a href=\"$add_edit_file?type=edit&id=".$sale["id"]."\"><img src='".M_URL."/images/icons/edit.png'></a>";
	if($sale['member_sale'] == 'y'){
		$user=get_user_detail_by_id($sale["uid"]);
		$customer_info = $sale["uid"].": ".$user["name"];
	}else{
		$customer_info = "<span style='color:orange;'>".__("Non-member").":</span> ".$sale['nm_name'].($sale['nm_contact']? ", $sale[nm_contact]" : '');
	}
	if($sale['stockist_sale']=='y'){
		if(!isset($users[$sale['sid']])){
			$users[$sale['sid']] = get_user_detail_by_id($sale['sid']);
		}
		$collection = "Stockist ID: $sale[sid], {$users[$sale['sid']]['name']}";
	}else{
		if($sale['mail_type'] == 'cr'){
			$collection = "Courier";
		}else{
			$collection = "Headquarter";
		}
	}	
	$sale_row.="
	<tr class='row$k".($sale['status']=='cancelled'? " cancelled" : "")."'>
		<td>$edit_link</td>
		<td>".$sale["id"]."</td>
		<td>".$customer_info."</td>
		<td>".number_format($sale['total_bv'], 2)."</td>
		<td>".$collection."</td>
		<td>".$r_payment_channel_d[$sale["payment_type"]]."</td>
		<td".($sale['status']=='cancelled'? " class='red bold'" : "").">".$r_status_d[$sale["status"]]."</td>
		<td><span class='bold'>".date($vars["date_format_short"], strtotime($sale["cdate"]))."</span> | ".date($vars["date_format"], strtotime($sale["edate"]))."</td>
	</tr>";
	$k=1-$k;
}

//listing text
$listing_text=replace_tag(($searching? __("Search returned <%x%> <%sale%>.") : __("Listing <%x%> <%sale%>.")), array("<%x%>"=>strval($total_record), "<%sale%>"=>$total_record>1? __("sales") : __("sale"))).($searching? " <a href='$this_file'>".__("Clear Search and Refresh")."</a>." : "");
$listing_text.=$point_list;
//listing
$sales_list=($errmsg || $msg? $errmsg.$msg : "").
"<input type='button' value='".__("Add Member Sale")."' onclick=\"window.location='$add_edit_file?type=add';\" />
$search_ui<br />\n
$listing_text $nav_link
<table class='aml_table' style='width:1200px;'>
	<tr class='aml_header'>
		<td width='18'><img src='".M_URL."/images/icons/edit.png'></td>
		<td>".__("ID")."</td>
		<td>".__("User")."</td>
		<td>".replace_tag(__("Total <%title%>"), array("<%title%>"=>__("BV")))."</td>
		<td>".__("Stockist Sale")."</td>
		<td>".__("Payment Type")."</td>
		<td>".__("Status")."</td>
		<td>".__("Sales Date (Calculation / Created)")."</td>
	</tr>
	$sale_row
</table>
</form>";
//#####END MEMBER SALES LIST#####

$content="<h2>$page_title</h2>$sales_list";

print format_admin_page($content, $this_title);

function msales_search($in_get){
	global $vars, $r_sale_point, $search_options;
	$db=$vars["db"];

	$get=$in_get;
	$search_type="and";
	$r_like_search=array("refno","nm_name","nm_contact");
	//format search string
	foreach($get as $field=>$value){
		$value=trim($value);
		//search checkbox option
		if(preg_match('/^_so_/', $field)){
			preg_match('/(?<=_so_).+(?=__)/', $field, $matchf);
			$f=$matchf[0];
			preg_match('/(?<=__).+$/', $field, $matchv);
			$v=$matchv[0];
			$r_searchquery[$f].=($r_searchquery[$f]? "," : "")."'$v'";
		}
		//db field name search
		if(substr($field, 0, strlen("_sp_"))=="_sp_"){
			if($field != '_sp_prefno'){
				if(strlen($value)){
					$db_fieldname=substr($field, strlen("_sp_"));
					$db_fieldname_q.=($db_fieldname_q? " and " : "")."(".(in_array($db_fieldname, $r_like_search)? format_search_field_like("s.".$db_fieldname, $value) : format_search_field("s.".$db_fieldname, $value)).")";
				}
			}
		}
	}
	if(isset($r_searchquery)){
		foreach($r_searchquery as $field => $query){
			$option_q.=($option_q? " and " : "")."s.$field in ($query)";
		}
	}else{
		$option_q="1=1";
	}
	if(strlen($get['_sp_prefno'])){
		$prod_str = format_search_field_like("refno", $get['_sp_prefno']);
		$prod_q = "s.id in (select distinct slid from $db->purchase_detail where $prod_str)";
	}else{
		$prod_q = "1=1";
	}
	$db_fieldname_q=$db_fieldname_q? $db_fieldname_q : "1=1";
	if(strlen($get['_sdf_day']) || strlen($get['_sdf_month']) || strlen($get['_sdf_year'])){
		if(!strlen($get['_sdf_day']) || !strlen($get['_sdf_month']) || !strlen($get['_sdf_year'])){
			$date_q="1=2";
		}else{
			$fdate="$get[_sdf_year]-".pad_length($get["_sdf_month"], 2)."-".pad_length($get["_sdf_day"], 2);
			if(!@checkdate($get['_sdf_month'], $get['_sdf_day'], $get['_sdf_year'])){
				$date_q="1=2";
			}else{
				if(strlen($get['_sdt_day']) || strlen($get['_sdt_month']) || strlen($get['_sdt_year'])){
					if(!strlen($get['_sdt_day']) || !strlen($get['_sdt_month']) || !strlen($get['_sdt_year'])){
						$date_q="1=2";
					}else{
						$tdate="$get[_sdt_year]-".pad_length($get["_sdt_month"], 2)."-".pad_length($get["_sdt_day"], 2);
						if(!@checkdate($get['_sdt_month'], $get['_sdt_day'], $get['_sdt_year'])){
							$date_q="1=2";
						}else{
							$date_q="s.cdate>='$fdate 00:00:00' and s.cdate<='$tdate 23:59:59'";
						}
					}
				}else{
					$date_q="s.cdate>='$fdate 00:00:00' and s.cdate<='$fdate 23:59:59'";
				}
			}
		}
	}else{
		$date_q="1=1";
	}

	$count_sql="select count(*) from $db->purchase s where $prod_q and $option_q and $db_fieldname_q and $date_q";
	$record_sql="select s.* from $db->purchase s where $prod_q and $option_q and $db_fieldname_q and $date_q order by id limit <%limit_start%>, <%limit%>";
	foreach($r_sale_point as $point_type){
		$return_sql[$point_type."_sql"] = "select sum(total_$point_type) from $db->purchase s where $prod_q and $option_q and $db_fieldname_q and $date_q";
	}
	
	$return_sql['count_sql'] = $count_sql;
	$return_sql['record_sql'] = $record_sql;

	return $return_sql;
}
?>